#include <iostream>
#include <netinet/in.h>
#include <strings.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;

void Usage(const std::string &proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(4);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    while (true)
    {
        int count = 5;
        bool isreconnect = false;
        int sockfd = -1;

        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            exit(1);
        }

        do
        {

            int n = connect(sockfd, (const struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                isreconnect = true;
                count--;
                std::cerr << "connect error, reconnect: " << count << std::endl;
                sleep(2);
            }
            else
            {
                break;
            }
        } while (count && isreconnect);

        if (count == 0)
        {
            cerr << "user offline..." << endl;
            break;
        }

        // while (true)
        // {
        string message;
        cout << "Please Enter# ";
        getline(cin, message);

        ssize_t n = write(sockfd, message.c_str(), message.size());
        if (n < 0)
        {
            std::cerr << "write error..." << std::endl;
        }

        char buffer[4096];
        n = read(sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            cout << buffer << endl;
        }
        // }
        close(sockfd);
    }
    return 0;
}